/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejercicio.practica8;

import java.util.Random;

/**
 *
 * @author manolo
 */
class Escritor extends Thread {

    //int rounds;
    lectorEscritor LE;
    private Random generator = new Random();

    public Escritor(lectorEscritor LE) {
       // this.rounds = rounds;
        this.LE = LE;
    }

    public void run() {
         while(true){
            try {
                Thread.sleep(generator.nextInt(500));
                LE.iniciaEscritura();
                Thread.sleep(generator.nextInt(500));
                LE.finalizaEscritura();
            } catch (java.lang.InterruptedException ex) {
                System.out.println("Error: " + ex);
            }

        }
    }
}

class Lector extends Thread {

  
    lectorEscritor LE;
    private Random generator = new Random();

    public Lector(lectorEscritor LE) {
        this.LE = LE;
    }

    public void run() {
       while(true){
            try {
                Thread.sleep(generator.nextInt(500));
                LE.iniciaLectura();
                Thread.sleep(generator.nextInt(500));
                LE.finalizaLectura();
            } catch (InterruptedException ex) {
                System.out.println("Error: " + ex);
            }
        }
    }
}

public class lectorEscritor {

    static int numeroLectores = 0;
    static boolean escribiendo = false;

    public void iniciaLectura() throws InterruptedException {

        synchronized (this) {
            while (escribiendo == true) {
                System.out.println("Libro ocupado por un escritor.");
                wait();
            }
            System.out.println("Un lector comienza la lectura");
            numeroLectores++;
        }
    }

    public void finalizaLectura() {
        synchronized (this) {
            if (--numeroLectores == 0) {
                System.out.println("Lecturas finalizadas.");
                notifyAll();
            }
        }
    }

    public void iniciaEscritura() throws InterruptedException {

        synchronized (this) {
            while (numeroLectores > 0 || escribiendo == true) {
                System.out.println("Libro ocupado, no se puede escribir.");
                wait();
            }
            System.out.println("Un escritor comienza la escritura");
            escribiendo = true;
        }
    }

    public void finalizaEscritura() {
        synchronized (this) {
            escribiendo = false;
            System.out.println("Escritor finaliza la escritura.");
            notifyAll();
        }
    }
}
